package View;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;

import libs.FileUtils;
import model.Load_ID3_Image;
import model.Load_ID3_Image_Exception;
import Controller.Action.Mp3LengthController;
import View.Components.JPanelTouch;
import View.Components.JScrollPaneTouch;
import View.Components.JViewPortTouch;
import View.Components.TouchButton;
import View.Components.TouchObjectContainer;

public class FileDirChooserFrame extends JPanel implements TouchObjectContainer{
	private static final long serialVersionUID = -6843198899237455885L;
	private FileChooser fileCho;
	public MainWindow mother;

	/**
	 * This method returns the variable fileCho.
	 * @return the fileCho
	 */
	public FileChooser getFileCho() {
		return fileCho;
	}


	/**
	 * This method sets the variable fileCho.
	 * @param fileCho the fileCho to set
	 */
	public void setFileCho(FileChooser fileCho) {
		this.fileCho = fileCho;
        fileCho.getjButton1().addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent evt) {
                        buttonFilesActionPerformed(evt);
                    }
                });
        fileCho.getjButton2().addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent evt) {
                        buttonFilesActionPerformed(evt);
                    }
                });
	}
	

    /**
     * The file list of the current directory.
     */
    private LinkedList<TouchButton> lstButtons = new LinkedList<TouchButton>();

    /**
     * TODO.
     */
    private GridBagLayout gbl = new GridBagLayout();

    /**
     * TODO.
     */
    private JPanelTouch mainPanel = new JPanelTouch();
    private TouchButton scrollUpButton = new TouchButton("^^^^");
    private TouchButton scrollDownButton = new TouchButton("vvvv");
    private JScrollPaneTouch scrollPane;
    private static final String START_DIRECTORY = "c:\\";
    private int scrollValue = 20;
    private BufferedImage standardImage = null;
    /**
     * Initializes the GUI elements.
     */
    public FileDirChooserFrame() {
        try {
            standardImage = ImageIO.read(ClassLoader.getSystemResource("test_kevin/mp3-icon.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //They see me scrollin, they hatin
        scrollPane = new JScrollPaneTouch(this.mainPanel);
        this.mainPanel.setLayout(this.gbl);
        this.setLayout(new BorderLayout());
        this.add(scrollUpButton,BorderLayout.PAGE_START);
        scrollUpButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent evt) {
                        buttonFilesActionPerformed(evt);
                    }
                });
        this.add(scrollPane,BorderLayout.CENTER);
        this.add(scrollDownButton, BorderLayout.PAGE_END);
        scrollDownButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent evt) {
                        buttonFilesActionPerformed(evt);
                    }
                });
        checkForButts();
    }
    public void startDirEtc() {
        setFileList(FileUtils.getFileListing(this.currentDir = new File(START_DIRECTORY), true));
    }
    /**
     * TODO.
     *
     * @param c Component to add
     * @param gridx x position
     * @param gridy y position
     * @param gridheight component height
     */
    private void addComponent(final Component c, final int gridx, final int gridy, final int gridheight) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.gridheight = gridheight;
        gbc.insets = new Insets(2, 2, 2, 2);
        this.gbl.setConstraints(c, gbc);
        this.mainPanel.add(c);
        this.repaint();
        this.validate();
    }

    /**
     * Changes dir according to the current action command.
     *
     * @param evt The performed action event.
     */
    private void buttonFilesActionPerformed(final ActionEvent evt) {
        System.out.println(evt.getActionCommand());
        if(evt.getSource() == this.scrollUpButton || evt.getSource() == this.scrollDownButton){
            if(evt.getSource() instanceof TouchButton){
                TouchButton butt = ((TouchButton) evt.getSource());
                if(butt == scrollDownButton)
                    this.scroll(+scrollValue );
                if(butt == scrollUpButton)
                    this.scroll(-scrollValue);
            }}
        else        if(evt.getSource() == this.fileCho.getjButton1() || evt.getSource() == this.fileCho.getjButton2()){
            if(evt.getSource() instanceof TouchButton){
                TouchButton butt = ((TouchButton) evt.getSource());
                if(butt == this.fileCho.getjButton2())
                    this.scroll(+scrollValue*5, fileCho.getjScrollPane1().getVerticalScrollBar() );
                if(butt == this.fileCho.getjButton1())
                    this.scroll(-scrollValue*5, fileCho.getjScrollPane1().getVerticalScrollBar());
            }}
        else
        onChangeDir(evt.getActionCommand());
    }
    private void scroll(int i, JScrollBar js) {
        js.setValue(js.getValue()+i);        
    }


    private File currentDir;
    public void onChangeDir(final String name) {
        try {
            final File newLocation = name.contentEquals("..") ? this.currentDir.getParentFile() : new File(this.currentDir.getCanonicalPath().concat(File.separator).concat(name));
            if (newLocation.isDirectory()) {
                this.currentDir = newLocation;
            }
        }
        catch (final IOException e) {
            e.printStackTrace();
            //TODO Logging
        }
        this.setFileList(FileUtils.getFileListing(this.currentDir, true));
    }
    
    private void scroll(int i) {
        JScrollBar js = this.scrollPane.getVerticalScrollBar();
        js.setValue(js.getValue()+i);
    }

    /**
     * Generates file list as JButtons.
     *
     * @param files Filenames
     */
    public void setFileList(final String[] files) {
        int i = 0;
        int j = 0;

        //Remove buttons
        if(fileCho != null && fileCho.getFilePanel() != null)
            this.fileCho.getFilePanel().removeAll();
        for (final TouchButton curButton : this.lstButtons) {
            this.mainPanel.remove(curButton);
        }

        //Add buttons
        for (final String curFile : files) {

            TouchButton tmpButton = new TouchButton(curFile);
            tmpButton.addActionListener(
                    new ActionListener() {

                        @Override
                        public void actionPerformed(final ActionEvent evt) {
                            buttonFilesActionPerformed(evt);
                        }
                    });

            if (curFile.endsWith(".mp3")) {
//                this.lstButtons.add(tmpButton);
//                this.addComponent(tmpButton, 1, i++, 1);
                SoundClip sc = new SoundClip();
                File fileLOL = null;
                try {
                    fileLOL = new File(this.currentDir.getCanonicalPath().concat(File.separator).concat(curFile));
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                BufferedImage bi = null;
                try{
                    bi = Load_ID3_Image.loadImage(fileLOL);
                    if(bi == null)
                        throw new NullPointerException();
                } catch(Load_ID3_Image_Exception ex){
                      bi = standardImage;
                } catch(NullPointerException e) {
                    bi = standardImage;
                }
                sc.getPanelPicture().setBi(bi);
                sc.getLabelRealTitel().setText(curFile.substring(0,curFile.indexOf('.')));
                this.getFileCho().getFilePanel().add(sc);
                sc.setButtList(sc, "Add");
                sc.setMp3File(fileLOL);
                sc.setMother(mother);
                new Mp3LengthController().actionPerformed(fileLOL, sc.getLabelRealLength());
                sc.repaint();
                sc.validate();
            }
            else {
                this.lstButtons.add(tmpButton);
                this.addComponent(tmpButton, 0, j++, 1);
            }
           JPanel jp = this.getFileCho().getFilePanel();
           Container c = jp;
           c.getParent().getParent().repaint();
           c.getParent().getParent().validate();
        }
        checkForButts();
        checkForFileChooserButts();
    }
    private void checkForFileChooserButts() {
        if(this.fileCho.getjScrollPane1().getVerticalScrollBar().isShowing()){
            this.fileCho.getjButton1().setEnabled(true);
            this.fileCho.getjButton2().setEnabled(true);
        }else{
            this.fileCho.getjButton1().setEnabled(false);
            this.fileCho.getjButton2().setEnabled(false);
        }
    }


    public void checkForButts(){
        if(this.scrollPane.getVerticalScrollBar().isShowing()){
            scrollUpButton.setEnabled(true);
            scrollDownButton.setEnabled(true);
        }else{
            scrollUpButton.setEnabled(false);
            scrollDownButton.setEnabled(false);
        }
        
    }
}
